package edu.bupt.softsec.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;

public class ReadDataFromFile {

  public static void main(String[] args) {
    // System.out.println(
    // parseLine("Lcom/1/1;-> Lcom/2/2;")[0] + " " + parseLine("Lcom/1/1;-> Lcom/2/2;")[1]);
    File txtRoot = new File("/Users/yujianbo/Desktop/relationTXT/");
    for (File f : txtRoot.listFiles()) {
      try {
        readFileToDB(f.getAbsolutePath());
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void readFileToDB(String filePath) throws Exception {
    // init connection
    Class.forName("org.postgresql.Driver").newInstance();
    String url = "jdbc:postgresql://192.168.1.184:5432/pgdb_ic3";
    Connection con = DriverManager.getConnection(url, "postgres", "postgres");

    File dataFile = new File(filePath);
    FileInputStream fis = new FileInputStream(dataFile);
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(isr);
    String line = "";
    WriteAliaes aliaes = new WriteAliaes();
    while ((line = br.readLine()) != null) {
      System.out.println(line);
      String result[] = parseLine(line);
      aliaes.insertDB(result[0], result[1], con);
    }

    // close
    br.close();
    isr.close();
    fis.close();
    con.close();
  }

  private static String[] parseLine(String s) {
    String source = s.split("->")[0].trim();
    String des = s.split("->")[1].trim();
    source = convert(source);
    des = convert(des);
    String[] re = new String[2];
    re[0] = source;
    re[1] = des;
    return re;
  }

  private static String convert(String s) {
    String re = s.substring(1, s.length() - 1);
    re = re.replaceAll("/", ".");
    return re;
  }

}
